﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bymed.SpineScan.DataModel;
using Bymed.SpineScan.Repository.Interface;
using Bymed.SpineScan.Service.Interface;
using Bymed.SpineScan.Service.Shared;
using Bymed.SpineScan.Service.Validation;

namespace Bymed.SpineScan.Service
{
    public class DiagnosticMessageReferenceService : ServiceBase<DiagnosticMessageReference>, IDiagnosticMessageReferenceService
    {
        public DiagnosticMessageReferenceService(IRepositoryFactory repositoryFactory) : base(repositoryFactory, new DiagnosticMessageReferenceValidator()) { }

        /// <summary>
        /// Synchronize the input DiagnosticMessageReference list with data source.
        /// Add new DiagnosticMessageReference. Update existing DiagnosticMessageReference. Delete removed DiagnosticMessageReference.
        /// </summary>
        /// <param name="entities">The input DiagnosticMessageReference list.</param>
        public void Synchronize(IList<DiagnosticMessageReference> entities)
        {
            using (RepositoryFactory)
            {
                RepositoryFactory.OpenSessionWithTransaction();
                var repository = RepositoryFactory.CreateDiagnosticMessageReferenceRepository();
                var entityCount = entities.Count();

                for (int i = 0; i < entityCount; i++)
                {
                    if (string.IsNullOrEmpty(entities[i].MessageTimestamp))
                    {
                        entities[i].MessageTimestamp = GeneralUtility.GetTimestamp();
                    }

                    entities[i].OrderIndex = i + 1;
                    repository.AddOrUpdate(entities[i]);
                }

                var existingEntityIds = entities.Select(m => m.MessageTimestamp).ToList();
                var removedEntities = repository.Query(m => !existingEntityIds.Contains(m.MessageTimestamp));

                repository.Delete(removedEntities);
                RepositoryFactory.Commit();
            }
        }
    }
}
